<?php

namespace app\service;

use app\dao\TitleDao;
use app\exception\ServiceException;
use think\facade\Cache;
use think\facade\Db;

class TitleService
{
    private $titleDao;
    public function __construct()
    {
        $this->titleDao = new TitleDao();
    }

    public function setCache($type = -1){
        if ($type == -1) {
            $information = $this->titleDao
                ->getAll();
        } else {
            $information = $this->titleDao
                ->findByType($type)
                ->getAll();
        }

        Cache::set('titInformation',$information,3600);
        return $information;
    }
    public function deleteCache() {
        $result = Cache::get('titInformation');
        if ($result != null) Cache::delete('titInformation');
        return true;
    }
    public function getInformation($type = -1){
        $typeCache = Cache::get('type');
        $result = Cache::get('titInformation');
        if ($typeCache == $type) {
            if ($result != null) return $result;
        }
        Cache::set('type',$type,3600);
        return $this->setCache($type);
    }

    public function createTitle($type,$title,$A,$B,$C,$D,$answer){
        if ($this->titleDao->findByTitle($title)->getOne() != null) throw new ServiceException('此题目已存在');
        try {
            $this->titleDao->create([
                'type' => $type,
                'title' => $title,
                'option_A' => $A,
                'option_B' => $B,
                'option_C' => $C,
                'option_D' => $D,
                'answer' => $answer
            ]);
            $this->deleteCache();
        } catch (\Exception $e) {
            throw new ServiceException('添加失败');
        }
        return $this->setCache();
    }

    public function editTitle($id,$type,$title,$A,$B,$C,$D,$answer){
        try {
            $result = $this->titleDao->edit($id,[
                'type' => $type,
                'title' => $title,
                'option_A' => $A,
                'option_B' => $B,
                'option_C' => $C,
                'option_D' => $D,
                'answer' => $answer
            ]);
            $this->deleteCache();
        } catch (\Exception $e) {
            throw new ServiceException('修改失败');
        }
        $this->setCache();
        return $result;
    }

    public function delTitle($id) {
        try {
            Db::startTrans();
            $result = $this->titleDao->delete($id);
            $this->deleteCache();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new ServiceException('删除失败');
        }
        $this->setCache();
        return $result;
    }



}